const axios = require("axios");
import logger from "../utils/log";
const { v4: uuidv4 } = require("uuid");

// 验证SSML内容和API URL
const validateParams = (ssml: string, key: string, apiUrl: string) => {
  const issues = [];
  
  // 检查API URL
  if (!apiUrl) {
    issues.push("API URL未提供");
  } else {
    try {
      new URL(apiUrl);
    } catch (e) {
      issues.push(`API URL格式无效: ${apiUrl}`);
    }
  }
  
  // 检查密钥
  if (!key) {
    issues.push("API密钥未提供");
  }
  
  // 检查SSML基本格式
  if (!ssml) {
    issues.push("SSML内容为空");
  } else if (!ssml.includes("<speak") && !ssml.includes("</speak>")) {
    issues.push("SSML内容可能不是有效的SSML格式");
  }
  
  return {
    valid: issues.length === 0,
    issues
  };
};

const thirdPartyApi = (ssml: string, key: string, apiUrl: string, retryCount = 3, retryInterval = 1000) => {
  // 验证参数
  const validation = validateParams(ssml, key, apiUrl);
  if (!validation.valid) {
    logger.error(`第三方API参数验证失败: ${validation.issues.join(', ')}`);
    return Promise.reject(new Error(`参数验证失败: ${validation.issues.join(', ')}`));
  }

  var config = {
    method: "post",
    url: apiUrl,
    responseType: "arraybuffer",
    headers: {
      "Authorization": `Bearer ${key}`,
      "X-Microsoft-OutputFormat": "riff-24khz-16bit-mono-pcm",
      "Content-Type": "application/ssml+xml",
      "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
    },
    data: ssml,
  };

  logger.info(`调用第三方API: ${apiUrl}`);
  logger.info(`使用的密钥: ${key ? key.substring(0, 4) + '****' : '未提供'}`);
  logger.info(`发送的SSML内容: ${ssml.substring(0, 100)}...`);
  logger.info(`请求头: ${JSON.stringify(config.headers)}`);
  
  return new Promise((resolve, reject) => {
    const attemptRequest = async (attempt = 1) => {
      try {
        const response = await axios(config);
        logger.info(`第三方API调用成功，状态码: ${response.status}`);
        logger.info(`响应类型: ${response.headers['content-type']}`);
        resolve(response.data);
      } catch (error) {
        logger.error(`第三方API调用失败 (尝试 ${attempt}/${retryCount}): ${error}`);
        
        // 记录详细的错误信息
        if (error.response) {
          // 服务器响应了错误状态码
          logger.error(`错误状态码: ${error.response.status}`);
          logger.error(`错误状态文本: ${error.response.statusText}`);
          logger.error(`响应头: ${JSON.stringify(error.response.headers)}`);
          
          // 如果响应不是二进制数据，尝试输出响应内容
          if (error.response.data && 
              typeof error.response.data === 'object' && 
              !(error.response.data instanceof Buffer || error.response.data instanceof ArrayBuffer)) {
            logger.error(`响应内容: ${JSON.stringify(error.response.data)}`);
          } else if (typeof error.response.data === 'string') {
            logger.error(`响应内容: ${error.response.data}`);
          }
        } else if (error.request) {
          // 请求已发送但没有收到响应
          logger.error(`未收到响应: ${error.request}`);
        } else {
          // 设置请求时发生错误
          logger.error(`请求错误: ${error.message}`);
        }
        
        if (attempt < retryCount) {
          logger.info(`将在 ${retryInterval}ms 后重试...`);
          setTimeout(() => attemptRequest(attempt + 1), retryInterval);
        } else {
          logger.error(`已达到最大重试次数 (${retryCount})，放弃请求`);
          reject(error);
        }
      }
    };
    
    attemptRequest();
  });
};

export default thirdPartyApi; 